import React, { Component } from 'react';
import Cursor from './Cursor';
import * as utils from './utils';

export default class Typist extends Component {

    static defaultProps = {
        className: '',
        delayGenerator: () => 150
    }

    constructor(props) {
        super(props);
        this.linesToType = ['欢迎光临 kazu 的个人博客！！🥳🥳🥳'];
        if (props.children) {
            this.linesToType = [props.children];
        }
    }

    state = {
        textLines: ['Hi！'],
    }

    componentDidMount() {
        this.typeAllLines();
    }

    delayGeneratorComp = () => {
        return this.props.delayGenerator();
    }

    typeAllLines(lines = this.linesToType) {
        utils.eachPromise(lines, this.typeLine)
    }

    typeLine = (line, lineIdx) => {
        utils.eachPromise(line, this.typeCharacter, lineIdx)
    }

    typeCharacter = (character, charIdx, lineIdx) => {
        console.log(character, lineIdx)
        return new Promise((resolve) => {
            const textLines = this.state.textLines.slice();

            textLines[lineIdx] += character;
            this.setState({ textLines });
            const delay = this.delayGeneratorComp();
            setTimeout(resolve, delay);
        });
    }

    render() {
        const { className } = this.props;
        const innerTree = this.state.textLines;

        return (
            <div className={`Typist ${className}`}>
                {innerTree}
                <Cursor />
            </div>
        );
    }
}
